package com.sunny.l57;

/**
 * @Author zsunny
 * @Date 2018/9/13 16:09
 * @Mail zsunny@yeah.net
 */
public class Solution {
    public ListNode reverseBetween(ListNode head, int m, int n) {
        if(m == n)
            return head;
        if(1 == m){
            ListNode node = head;
            for(int i=0;i<n;i++){
                node = node.next;
            }
            ListNode p1 = null;
            ListNode p2 = head;
            ListNode p3 = head.next;
            while (node != p2){
                p2.next = p1;
                p1 = p2;
                p2 = p3;
                if(node != p3)
                    p3 = p3.next;
            }
            head.next = node;
            head = p1;
            return head;
        }else{
            ListNode nodeBack = null;
            ListNode nodeM = head;
            for(int i=0;i<m-1;i++) {
                nodeBack = nodeM;
                nodeM = nodeM.next;
            }
            ListNode nodeN = head;
            for(int i=0;i<n;i++)
                nodeN = nodeN.next;
            ListNode p1 = null;
            ListNode p2 = nodeM;
            ListNode p3 = nodeM.next;
            while (nodeN != p2){
                p2.next = p1;
                p1 = p2;
                p2 = p3;
                if(nodeN != p3){
                    p3 = p3.next;
                }
            }
            nodeBack.next = p1;
            nodeM.next = nodeN;
            return head;
        }
    }
}

class ListNode {
    int val;
    ListNode next;
    ListNode(int x) {
     val = x;
     next = null;
    }
}
